package com.zhang.crm.handler;

import com.zhang.crm.constant.Constants;
import com.zhang.crm.pojo.TUser;
import com.zhang.crm.result.R;
import com.zhang.crm.service.RedisService;
import com.zhang.crm.util.JSONUtil;
import com.zhang.crm.util.JWTUtil;
import com.zhang.crm.util.ResponseUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class ZhangLoginSuccessHandler implements AuthenticationSuccessHandler {
    @Resource
    private RedisService redisService;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //状态保持
        TUser tUser = (TUser) authentication.getPrincipal();

        //生成jwt
        String jwt = JWTUtil.createJWT(JSONUtil.toJSON(tUser));

        //写入redis
        redisService.set(Constants.REDIS_JWT_KEY + tUser.getId(), jwt); //选择不同过期时间
        Boolean flag = false;
        String rememberMe = request.getParameter("rememberMe");
        if (Boolean.parseBoolean(rememberMe)){
            //证明勾选了记住我
            flag =  redisService.expire(Constants.REDIS_JWT_KEY + tUser.getId(), 7L, TimeUnit.DAYS);
        }else {
            flag = redisService.expire(Constants.REDIS_JWT_KEY + tUser.getId(), 30L, TimeUnit.MINUTES);
        }
        if (!flag){
            throw new RuntimeException("过期时间设置失败！");
        }

        //登录成功，返回json
        R r = R.OK(jwt);

        ResponseUtil.write(response,JSONUtil.toJSON(r));
    }
}
